﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;
using System.Diagnostics;
using System.Reflection;

namespace CtrlLog
{
    public class ClassLog
    {
        string LogFileName;
        DataTable dtLog = new DataTable();

        public ClassLog(string ExeFileName)
        {
            string logFilePath = Path.GetDirectoryName(ExeFileName) + "\\LOG";
            if(Directory.Exists(LogFileName)==false)
            {
                Directory.CreateDirectory(logFilePath);
            }

            LogFileName = logFilePath + "\\"+DateTime.Now.ToString("yyyy-MM-dd")+".xml";
            if (File.Exists(LogFileName))
            {
                dtLog.ReadXml(LogFileName);
            }
            else
            {
                dtLog.TableName = "ClassLog";
                dtLog.Columns.Add("时间");                
                dtLog.Columns.Add("方法");
                dtLog.Columns.Add("参数");
                dtLog.Columns.Add("目标");
                dtLog.Columns.Add("信息");
            }
        }

        public void Append(MethodBase aMethodBase, Exception aException)
        {
            DataRow drNew = dtLog.Rows.Add();
            drNew["时间"] = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
            drNew["方法"] = aMethodBase.DeclaringType.FullName + "." + aMethodBase.Name;
            drNew["参数"] = GetParmText(aMethodBase);
            drNew["目标"] = aException.TargetSite.DeclaringType.FullName;
            drNew["信息"] = aException.Message;
            GetParmText(aMethodBase);
            dtLog.WriteXml(LogFileName, System.Data.XmlWriteMode.WriteSchema);
        }

        private string GetParmText(MethodBase aMethodBase)
        {
            string result = string.Empty;
            ParameterInfo[] pia= aMethodBase.GetParameters();
            for (int i = 0; i < pia.Length; i++)
            {
                result += pia[i].Name + ";";
            }
            return result;
        }
    }
}
